package com.tg.app.activity.device;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.appbase.custom.constant.CommonConstants;
import com.base.BaseActivity;
import com.hjq.permissions.Permission;
import com.tange.ai.core.router.annotations.Destination;
import com.tange.base.toolkit.PreferenceUtil;
import com.tange.base.toolkit.StatusBarUtil;
import com.tange.base.toolkit.StringUtils;
import com.tange.core.access.token.Authentication;
import com.tange.core.access.token.Token;
import com.tange.core.backend.service.http.HttpConfigurations;
import com.tange.feature.development.toolkit.HttpInterceptNotification;
import com.tange.feature.router.distribution.TDestinations;
import com.tange.module.camera.hub.CameraHub;
import com.tange.module.log.XLogProxy;
import com.tange.module.statistics.TangeBizEventReport;
import com.tange.module.statistics.TangeBizStatisticsConstants;
import com.tg.app.R;
import com.tg.app.activity.device.list.DeviceListFragment;
import com.tg.app.activity.device.list.DeviceListPushConfig;
import com.tg.app.activity.device.list.HomeFragment;
import com.tg.appcommon.android.PermissionUtil;
import com.tg.appcommon.android.TGApplicationBase;
import com.tg.appcommon.android.TGLog;
import com.tg.loginex.helper.LoginHelper;
import com.tg.push.initialization.MessagePush;

import java.util.List;

@Destination(url = TDestinations.DEVICE_HOME, description = "首页")
public class DeviceListActivity extends BaseActivity implements DeviceListPushConfig {

    private static final String TAG = "DeviceListActivityTAG";

    /**
     * 1 = 双模式（默认），见 customize_layout.xml 的 layout_tange_global_home_page_style
     */
    private static final int LAYOUT_STYLE_STANDARD = 1;


    public static final String LIST_ATTR_PAGE = "page";
    public static final String LIST_ATTR_LIMIT = "limit";
    public static final String EXT_NOTIFICATION_UUID = "ext_notification_uuid";
    public static final String ACTION_UPDATE_LIST = "action_update_list";
    public static final int DEVICE_LIST_ACTIVITY_REQUEST_CODE = 100;

    private DeviceListFragment deviceListFragment;
    private HomeFragment homeFragment;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏

        super.onCreate(savedInstanceState);
        TGLog.i(TAG, "onCreate: list activity show ------------------------------");
        String lastChannel = LoginHelper.getLastLoginChannel();
        String account = PreferenceUtil.getString(this, CommonConstants.PRE_USER_NAME);
        int userId = PreferenceUtil.getInt(this, CommonConstants.PRE_USER_ID);
        CameraHub.getInstance().setUserId(userId);
        TGLog.i(TAG, "onCreate: login channel " + lastChannel);
        TGLog.i(TAG, "onCreate: login account " + account);
        TGLog.i(TAG, "onCreate: login userId " + userId);

        StatusBarUtil.setStatusBarTransparent(this);
        hideActionBar();
        initView();

        setContentView(R.layout.activity_tange_home_container);

        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setNavigationBarColor(Color.WHITE);
        }

        homeFragment = HomeFragment.newInstance(getIntent().getExtras());
        showFragment(homeFragment);

        try {
            long size = XLogProxy.getLogDirSize(this);
            TangeBizEventReport.reportValue(this, TangeBizStatisticsConstants.App_Log_Dir_Size_KB, (int) size);
            TGLog.i(TAG, "onCreate: log-dir-size = " + size);
        } catch (Throwable ex) {}

        HttpInterceptNotification.showNotification(this);

        MessagePush.INSTANCE.requireBinding(getApplicationContext(), pushingConfiguration -> TGLog.i(TAG, "[onCreate][message-push-binding] ret = " + pushingConfiguration));
        NotificationChannel();
    }


    private void  NotificationChannel(){
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            List<NotificationChannel> pushs = mNotificationManager.getNotificationChannels();
            for (NotificationChannel channel: pushs) {
                TGLog.i(TAG,"NotificationChannel channel: "+channel.getId()+" name:"+channel.getName()+" "+channel.getDescription());
            }
        }
    }
    private void showFragment(Fragment fragment) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.child_container, fragment);
        transaction.commitNow();
    }

    @Override
    protected void initView() {}

    @Override
    protected void onRestart() {
        super.onRestart();

        if (homeFragment != null) {
            homeFragment.onActivityRestart();
        }
        if (deviceListFragment != null) {
            deviceListFragment.onActivityRestart();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        TGLog.d("DevceListActivity onNewIntent " + intent.getExtras());
        TGLog.i(TAG, "[onNewIntent] intent = " + intent);
        if (intent != null) {
            TGLog.i(TAG, "[onNewIntent] intent.extras = " + intent.getExtras());
        }
        if (homeFragment != null) {
            homeFragment.onNewIntent(intent);
        }
        if (deviceListFragment != null) {
            deviceListFragment.onNewIntent(intent);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (deviceListFragment != null) {
                boolean ret = deviceListFragment.onBackKeyClicked();
                if (ret) {
                    return true;
                }
            }

            if (homeFragment != null) {
                boolean ret = homeFragment.onBackKeyClicked();
                if (ret) {
                    return true;
                }
            }

            return super.onKeyDown(keyCode, event);
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        TGLog.i(TAG, "onActivityResult requestCode = " + requestCode);

        if (deviceListFragment != null) {
            deviceListFragment.onActivityResult(requestCode, resultCode, data);
        }
        if (homeFragment != null) {
            homeFragment.onActivityResult(requestCode, resultCode, data);
        }
        if (resultCode==DeviceBusinessActivity.RESULT_PERMISSION){
            PermissionUtil permissionUtil = new PermissionUtil(this);
            permissionUtil.checkPermissionFirst(null,  null, true, null, null, Permission.ACCESS_FINE_LOCATION, Permission.ACCESS_COARSE_LOCATION);

        }
    }

    @Override
    public void onBackPressed() {
        moveTaskToBack(true);
        TGLog.d(TAG, "onBackPressed");
        CameraHub.getInstance().removeAll();
    }

    @Override
    protected void onDestroy() {
        TGLog.d(TGLog.TAG, "onDestroy");
        super.onDestroy();
    }
}
